package com.ktvme.MqTest

import groovy.util.logging.Slf4j

/**
 * @author fanwu 编写于 2017/12/27.
 *
 * 用于金额转换，避免出现float 计算失真
 */
@Slf4j
class MoneyUtil {
    /**
     * 将分为单位的数值转换为以元为单位供显示用的字符串
     */
    static String convertFen2Yuan(int accountInFen) {
        if (0 == accountInFen) { //不少数据为0
            return "0"
        }

        String fenStr = "" + accountInFen
        if (fenStr.length() == 1) {
            fenStr = "00" + fenStr
        } else if (fenStr.length() == 2) {
            fenStr = "0" + fenStr
        }

        def prerevenue = fenStr.substring(0, fenStr.length() - 2)
        def afterRevenue = fenStr.substring(fenStr.length() - 2, fenStr.length())

        if ("00" == afterRevenue) {
            return prerevenue
        }
        return prerevenue + "." + afterRevenue
    }


    /**
     * 将字符串的元单位金额，转换成以分为单位的int 值
     */
    static int convertYuan2Fen(String accoutInYuan) {

        if ("0" == accoutInYuan || null == accoutInYuan) {
            return 0
        }

        def index = accoutInYuan.indexOf('.')

        if (index < 0) { //没小数点
            return toInteger(accoutInYuan) * 100
        }

        if (index == accoutInYuan.length() - 3 && index > 0) { //有小数点, 2位小数
            def fenValue = accoutInYuan.replace('.', '')
            return toInteger(fenValue)
        }


        if (index == accoutInYuan.length() - 2 && index > 0) { //1位小数
            def fenValue = accoutInYuan.replace('.', '')
            return toInteger(fenValue) * 10
        }

        //大于等于3位小数，减尾，递归
        String newString = accoutInYuan.substring(0, accoutInYuan.length() - 1)
        return convertYuan2Fen(newString)
    }

    private static int toInteger(String number) {
        int i = 0
        try {
            i = number.toInteger()
        } catch (Exception e) {
            log.error("线下数据进行金额转换时出现转换异常，number:${number} 转换为数字时出现异常".toString(), e)
        }
        return i
    }


}
